﻿/// <reference name="MicrosoftAjax.debug.js" />

Type.registerNamespace('HttpHelper');


HttpHelper.AjaxAction = function () {
}
HttpHelper.AjaxAction.prototype = {
    /// <summary>
    /// Inicia la acción asincrónica
    /// </summary>
    /// <param name="options" type="object" mayBeNull="false" optional="false">
    /// Opciones para iniciar la llamada asincrónica. Es obligatorio setear la propiedad 'url'.
    /// Otras propiedades posibles son:
    /// update: el id del elemento donde se mostrará la respuesta
    /// updateType: puede ser 'replaceContent' (default) o 'replace'
    /// </param>
    /// <param name="options" type="String" mayBeNull="true" optional="true">
    /// Datos que se enviarán al server como post. Estos datos deben estar Url-encoded
    /// </param>
    invoke: function (options, data, onRequestFinished) {
        var request = new Sys.Net.WebRequest();
        request.set_url(options.url);
        request.set_userContext(options);
        if (data) {
            request.set_body(data);
            request.set_httpVerb('POST');
            if (options.format == 'json') {
                 request.get_headers()['Content-Type'] = 'application/json; charset=utf-8';
            }
        }
        else {
            request.set_httpVerb('GET');
        }
        request.add_completed(Function.createDelegate(this, this._onCompleted));
        request.add_completed(Function.createDelegate(this, onRequestFinished));
        //Mejora: agregar "Cargando..."
        request.invoke();
    },
    
    _onCompleted: function (executor, eventArgs) {
        if (executor.get_responseAvailable() && executor.get_statusCode() === 200)
        {
            var options = executor.get_webRequest().get_userContext();
            if (options.update)
            {
                var updateElement;
                if (options.updateType === 'replace') {
                    updateElement = $get(options.update).parentNode;
                }
                else { //replaceContent by default
                    updateElement = $get(options.update);                
                }
                updateElement.innerHTML = executor.get_responseData();
                updateElement = null;
            }
        }
        if (executor.get_statusCode() === 500) {
            alert(executor.get_responseData());
        }
    }
}
HttpHelper.AjaxAction.registerClass('HttpHelper.AjaxAction');


HttpHelper.encodeFormElements = function(containerElement) {
    /// <summary>
    /// Helper function that encodes all form elements within a passed DOM Element
    /// </summary>
    /// <param name="parent" type="object" mayBeNull="false" optional="false">
    /// The parent DOM Element which contains all the form elements to be encoded. 
    /// Note that this is not necessarilly a 'form" element.
    /// </param>
    var formBuilder = new Sys.StringBuilder();
    var formElements;
    formElements = containerElement.getElementsByTagName('INPUT');
    for (var i = 0; i < formElements.length; i++) {
        var element = formElements[i];
        var name = element.name;
        if (name == '') {
            continue;
        }
        if ((element.type === 'text') || (element.type === 'password') || (element.type === 'hidden') || (((element.type === 'checkbox') || (element.type === 'radio')) && (element).checked)) {
            formBuilder.append(name);
            formBuilder.append('=');
            formBuilder.append(encodeURIComponent(element.value));
            formBuilder.append('&');
        }
    }
    formElements = containerElement.getElementsByTagName('SELECT');
    for (var i = 0; i < formElements.length; i++) {
        var element = formElements[i];
        var name = element.name;
        if (name == '') {
            continue;
        }
        var selectElement = element;
        for (var j = 0; j < selectElement.options.length; j++) {
            var option = selectElement.options[j];
            if (option.selected) {
                formBuilder.append(name);
                formBuilder.append('=');
                formBuilder.append(encodeURIComponent(option.value));
                formBuilder.append('&');
            }
        }
    }
    formElements = containerElement.getElementsByTagName('TEXTAREA');
    for (var i = 0; i < formElements.length; i++) {
        var element = formElements[i];
        var name = element.name;
        if (name == '') {
            continue;
        }
        formBuilder.append(name);
        formBuilder.append('=');
        formBuilder.append(encodeURIComponent(element.value));
        formBuilder.append('&');
    }
    formElements = null;
    containerElement = null;
    return formBuilder.toString();
}